<script setup lang="ts">
import { onBeforeMount, onMounted, type Ref, ref } from 'vue'
import Hls from 'hls.js'

const url = 'http://120.25.190.38:8080/live/tianqing.m3u8'
const streamEl: Ref<HTMLMediaElement | null> = ref(null)
let hls = new Hls({
  debug: true,
  enableWorker: true,
  lowLatencyMode: true,
  backBufferLength: 90,
})

function init() {
  if (hls != null) {
    close()
  }
  hls = new Hls()
  hls.loadSource(url)
  hls.attachMedia(streamEl.value)
  hls.on(Hls.Events.MANIFEST_PARSED, () => {
    console.log(`successfully loaded`)
  })
  hls.on(Hls.Events.ERROR, (reason) => {
    console.log(`An error raised ${reason}`)
    init()
  })
}

function close() {
  if (streamEl.value) {
    streamEl.value.pause()
    if (hls) {
      hls.detachMedia()
      hls.destroy()
      hls = null
    }
  }
}

onBeforeMount(init)

onMounted(() => {


})


</script>


<template>
  <div class="chatroom__middle__root">
    <video id="media__stream__el" ref="streamEl" controls autoplay></video>
    <div class="ct">
      <button @click="init">init</button>
      <button @click="streamEl.play">play</button>
      <button @click="streamEl.pause">pause</button>
      <button @click="close">close</button>
    </div>
  </div>
</template>

<style lang="scss">
.chatroom__middle__root {
  display: flex;
  flex-direction: column;
}

#media__stream__el {
  width: 100%;
  aspect-ratio: calc(16 / 9);
}

.ct {
  height: 50px;
}

</style>